import Ux from 'ux';
import Ix from '../../_internal/ix';
import React from 'react';
import {Icon} from 'antd';

const _configuration = (reference) => {
    const internal = Ux.fromHoc(reference, "config");
    const {config = {}} = reference.props;
    const $config = Ux.clone(internal);
    // user
    if (config.user) {
        // 传入 user 优先
        $config.user = config.user;
        const params = {user: $config.user};
        $config.validation = Ux.formatExpr($config.validation, params, true);
        $config.window = Ux.formatExpr($config.window, params, true);
    }

    // linker
    if (Ux.isNotEmpty(config.linker)) {
        $config.linker = Ux.clone(config.linker);
    }

    // query -> ajax["params.criteria"];
    if (config.query) {
        Object.assign($config.ajax["params.criteria"], config.query);
    }
    // 必须解析
    $config.ajax = Ux.aiExprAjax($config.ajax);
    return $config;
}

const _rxTree = (reference) => (keys = [], item = {}) => {
    const {node: {props}} = item;
    const {data = {}} = props;

    let {$filters = {}, $config = {}} = reference.state;
    $filters = Ux.clone($filters);
    $filters[""] = true;

    const condTree = $filters["$tree"] ? $filters["$tree"] : {};
    const {marker = {}} = $config;
    const tips = marker[data.mode];
    const field = tips.field;
    if (0 < keys.length) {
        condTree[field] = keys;
    } else {
        condTree[field] = "__DELETE__";
    }
    $filters["$tree"] = condTree;

    reference.setState({
        $filters, $loading: true
    });
    Ux.toLoading(() => {
        const {onClick} = reference.state;
        if (Ux.isFunction(onClick)) {
            onClick();
        }
    })
}

const _rxSearch = (reference, config = {}) => (text) => {
    let {$filters = {}} = reference.state;
    $filters = Ux.clone($filters);
    $filters[""] = true;

    const condition = [];
    const {search = {}} = config;
    Object.keys(search).forEach(key => condition.push(key));
    const condSearch = $filters["$keyword"] ? $filters["$keyword"] : {};
    if (text) {
        condition.forEach(cond => condSearch[cond] = text);
        condSearch[""] = false; // Or的语句
    } else {
        condition.forEach(cond => condSearch[cond] = "__DELETE__");
    }
    $filters["$keyword"] = condSearch;
    reference.setState({$filters, $loading: true});
    Ux.toLoading(() => {
        const {onClick} = reference.state;
        if (Ux.isFunction(onClick)) {
            onClick();
        }
    })
};

const treeConfig = (reference, config = {}, state) => {
    // 部门树 / 组树
    const {tree = {}, marker = {}} = config;
    const deptData = Ux.onDatum({state}, "user.departments");
    deptData.forEach(each => {
        each.parentId = each.deptId;
        each.mode = "DEPT";
        const icon = Ux.configIcon(marker['DEPT']);
        if (icon) {
            each.icon = (<Icon {...icon}/>)
        }
    });
    const teamData = Ux.onDatum({state}, "user.teams");
    teamData.forEach(each => {
        if (each['teamId']) {
            each.parentId = each['teamId'];
        } else {
            each.parentId = each['deptId'];
        }
        each.mode = "TEAM";
        const icon = Ux.configIcon(marker['TEAM']);
        if (icon) {
            each.icon = (<Icon {...icon}/>)
        }
    })

    const deptTree = Ux.toTree(deptData.concat(teamData), {
        parent: 'parentId',
        text: "name"
    });

    const $treeDept = {
        key: "rootDept",
        title: tree['dept'],
        checkable: false,
        children: deptTree
    }
    // 业务组配置
    const groupData = Ux.onDatum({state}, "ajax.groups");
    groupData.forEach(each => {
        each.mode = "GROUP";
        const icon = Ux.configIcon(marker['GROUP']);
        if (icon) {
            each.icon = (<Icon {...icon}/>)
        }
    });
    const groupTree = Ux.toTree(groupData, {
        parent: "parentId",
        text: 'name'
    })

    const $treeGroup = {
        key: 'rootGroup',
        title: tree['group'],
        checkable: false,
        children: groupTree,
    }

    const $tree = {};
    $tree.treeData = [
        $treeDept,
        $treeGroup
    ]
    $tree.defaultExpandAll = true;
    $tree.checkable = true;
    $tree.selectable = false;
    $tree.showIcon = true;
    // 修改 $filters
    $tree.onCheck = _rxTree(reference);
    return $tree;
}

export default {
    componentInit: (reference = {}) => {
        const assist = Ux.fromHoc(reference, "assist");
        const ref = Ux.onReference(reference, 1);
        return Ux.asyncAssist(assist, ref, {}).then(state => {
            // 合并配置
            const config = _configuration(reference);
            /*
             * 各部分组件配置处理
             */
            const dialog = Ix.dialogConfig(reference, config);
            const onClick = Ix.dialogClick(reference, config);

            const search = Ix.searchConfig(reference, config);
            search.onSearch = _rxSearch(reference, config);
            // 通用表格方法
            const table = Ix.tableConfig(reference, config);
            const tree = treeConfig(reference, config, state);
            const attrs = {
                onClick, dialog, $ready: true,
                table, search, tree,
            };
            /*
             * 非表单模式下专用，$keySet 结构
             * {
             *     "key": "xxxxx"
             * }
             */
            Object.assign(state, {
                ...attrs,
                $visible: false,
                $loading: false,
                $data: [],
                $keySet: undefined,
                $config: config,    // 配置信息
            })
            Ux.xtLazyInit(reference, {state, config});
            // reference.setState(state);
        })
    },

    yoPager: Ix.tablePager,
    yoCombine: Ix.dialogCombine,
    yoSelected: (reference, table = {}) => {
        const {$keySet} = reference.state;
        if (table.rowSelection) {
            if ($keySet) {
                // P1：state 状态中高优先级
                table.rowSelection.selectedRowKeys = [$keySet.key];
            } else {
                // P2：props 属性中低优先级，是否外部传入
                const {$keySet} = reference.props;
                if ($keySet) {
                    table.rowSelection.selectedRowKeys = [$keySet.key];
                } else {
                    table.rowSelection.selectedRowKeys = [];
                }
            }
        }
        return table;
    },
    /* 生命周期 constructor */
    yoValue: (reference, jsx = {}) => {
        const inputAttrs = Ux.valueLimit(jsx);
        if (undefined === inputAttrs.value) {
            /*
             * 只有 undefined 的时候触发
             */
            const {$defaultValue} = reference.state;
            if ($defaultValue) {
                inputAttrs.value = $defaultValue;
            }
        }
        return inputAttrs;
    },
}